package com.fhsk.file.manager.controller;

import com.fhsk.file.business.entity.bo.user.UserBo;
import com.fhsk.file.business.entity.vo.user.UserVo;
import com.fhsk.file.business.service.IUserService;
import com.fhsk.file.common.utils.RSAUtil;
import com.fhsk.file.common.vo.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/login")
@Api(value = "", tags = "登录管理")
public class LoginController {

    @Resource
    private IUserService userService;

    @Value("${server.encrypt.publicKey}")
    private String publicKey;

    private final static String PUBLICKEYSTR = "publicKeyStr";

    private static final String SYSTEM_CONFIG = "system:config";

    private static final String AUTH_ROLES = "AUTH_ROLES";

    private static final String PARAM_VALUE = "paramValue";

    private static final String ACCOUNT_LOCK_TIMES = "ACCOUNT_LOCK_TIMES";

    private static final String LOGIN_TIMES = "LOGIN_TIMES";

    /**
     * 获取非对称加密key
     *
     * @param request servletRequest
     * @return 公钥
     */
    @ApiOperation("获取非对称加密key")
    @GetMapping(value = "/toLogin")
    public AjaxResult toLogin(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>(4);
        map.put(PUBLICKEYSTR, publicKey);
        return AjaxResult.success(map);
    }

    /**
     * 用户登录
     *
     * @param user 用户bo
     * @return 登录结果
     */
    @ApiOperation("用户登录")
    @PostMapping(value = "/login")
    public AjaxResult login(@Validated @RequestBody UserBo user) {
        UserVo loginUser = userService.login(user);
        if (loginUser != null) {
            loginUser.setPassword(null);
            return AjaxResult.success(loginUser);
        }
        return AjaxResult.fail("登录失败!请重试");
    }

    /**
     * 开发用登陆
     *
     * @param user 用户bo
     * @return 登录结果
     */
    @ApiOperation("开发用登陆")
    @PostMapping(value = "/logins")
    public AjaxResult logins(@Validated @RequestBody UserBo user, HttpServletRequest request) throws Exception {
        //获取未加密密文
        String password = user.getPassword();
        //开发自己使用自动加密
        String encryPassword = RSAUtil.publicEncrypt(password, publicKey);
        //设置新的密码
        user.setPassword(encryPassword);
        //使用通用登录
        UserVo loginUser = userService.login(user);
        if (loginUser != null) {
            loginUser.setPassword(null);
            return AjaxResult.success(loginUser);
        }
        return AjaxResult.fail("登录失败!请重试");
    }
}
